/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.handler.esmtp;

import com.googlecode.asyncmail.smtp.SMTPResponse;
import com.googlecode.asyncmail.smtp.SMTPResponseImpl;
import com.googlecode.asyncmail.smtp.SMTPRetCode;
import com.googlecode.asyncmail.smtpserver.SMTPSession;
import com.googlecode.asyncmail.smtpserver.core.CommandHandler;
import com.googlecode.asyncmail.smtpserver.handler.HeloCmdHandler;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * Handles EHLO command
 */
public class EhloCmdHandler extends HeloCmdHandler implements CommandHandler {

    /**
     * The name of the command handled by the command handler
     */
    private final static String COMMAND_NAME = "EHLO";

    private List<EhloExtension> ehloExtensions;

    /**
     * Handler method called upon receipt of a EHLO command. Responds with a
     * greeting and informs the client whether client authentication is
     * required.
     * 
     * @param session
     *                SMTP session object
     * @param argument
     *                the argument passed in with the command by the SMTP client
     */
    private SMTPResponse doEHLO(SMTPSession session, String argument) {
        SMTPResponseImpl resp = new SMTPResponseImpl();
        resp.setRetCode(SMTPRetCode.MAIL_OK);

        session.getConnectionState().put(SMTPSession.CURRENT_HELO_MODE,
                COMMAND_NAME);

        resp.appendLine(new StringBuffer(session.getConfigurationData()
                .getHelloName()).append(" Hello ").append(argument)
                .append(" (").append(session.getRemoteHost()).append(" [")
                .append(session.getRemoteIPAddress()).append("])"));

        processExtensions(session, resp);

        resp.appendLine("PIPELINING");
        resp.appendLine("ENHANCEDSTATUSCODES");
        resp.appendLine("8BITMIME");
        return resp;

    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.core.CommandHandler#getImplCommands()
     */
    public Collection<String> getImplCommands() {
        Collection<String> implCommands = new LinkedList<String>();
        implCommands.add(COMMAND_NAME);

        return implCommands;
    }

    /**
     * @see com.googlecode.asyncmail.common.ExtensibleHandler#getMarkerInterfaces()
     */
    public List<Class<?>> getMarkerInterfaces() {
        List<Class<?>> classes = super.getMarkerInterfaces();
        classes.add(EhloExtension.class);
        return classes;
    }

    /**
     * @see com.googlecode.asyncmail.common.ExtensibleHandler#wireExtensions(java.lang.Class,
     *      java.util.List)
     */
    @SuppressWarnings("unchecked")
    @Override
    public void wireExtensions(Class<?> interfaceName, List<?> extension) {
        super.wireExtensions(interfaceName, extension);
        if (EhloExtension.class.equals(interfaceName)) {
            this.ehloExtensions = (List<EhloExtension>) extension;
        }
    }

    /**
     * Process the ehloExtensions
     * 
     * @param session
     *                SMTPSession
     * @param resp
     *                SMTPResponseImpl
     */
    private void processExtensions(SMTPSession session, SMTPResponseImpl resp) {
        if (ehloExtensions != null) {
            int count = ehloExtensions.size();
            for (int i = 0; i < count; i++) {
                List<String> lines = ehloExtensions.get(i)
                        .getImplementedEsmtpFeatures(session);
                if (lines != null) {
                    for (int j = 0; j < lines.size(); j++) {
                        resp.appendLine(lines.get(j));
                    }
                }
            }
        }
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.core.AbstractHookableCmdHandler#doCoreCmd(com.googlecode.asyncmail.smtpserver.SMTPSession,
     *      java.lang.String, java.lang.String)
     */
    protected SMTPResponse doCoreCmd(SMTPSession session, String command,
            String parameters) {
        return doEHLO(session, parameters);
    }

}
